import re
import pandas as pd

def parse_movie_data(file_content):
    # 定义正则表达式模式
    pattern = re.compile(
        r"\*+\s*"  # 分隔符
        r"(?P<title>.*?)\s*\n"  # 电影名称
        r"(?P<rating>\d\.\d)\s*\n"  # 评分
        r"导演:\s*(?P<director>.*?)\s*主演:\s*(?P<actors>.*?)\s*\n"  # 导演和演员
        r"\s*(?P<year>\d{4}).*?/\s*(?P<country>.*?)\s*/\s*(?P<genre>.*?)\s*\n"  # 年份/产地/类型
        r"(?P<quote>.*?)\s*\n"  # 金句
        r"(?P<poster>https://.*?)\s*\*+"  # 海报链接
    )
    
    movies = []
    for match in pattern.finditer(file_content):
        movie = match.groupdict()
        # 处理可能的多余空格和换行符
        for key in movie:
            movie[key] = movie[key].strip()
        movies.append(movie)

    print(len(movies))
    return movies

# 读取文件内容
with open('movies.txt', 'r', encoding='utf-8') as f:
    content = f.read()

# 解析数据
movies = parse_movie_data(content)

# 创建DataFrame
df = pd.DataFrame(movies)

# 显示前几行数据
print(df.head())

# 保存为CSV文件
df.to_csv('movies.csv', index=False, encoding='utf-8-sig')
